package dp;

/**
 * 粉碎石头问题转化为0-1背包问题,将石头分为重量尽量相等的两堆
 */
public class ds1049 {
    public static void main(String[] args) {
        System.out.println(lastStoneWeightII(new int[]{2,7,4,1,8,1}));
    }
    public static int lastStoneWeightII(int[] stones) {
        int sum = 0;
        for (int i : stones) {
            sum += i;
        }
        int tar = sum / 2;
        int[] dp = new int[tar + 1];
        for (int i = 0; i < stones.length; i++) {
            for (int j = tar; j >= stones[i] ; j--) {
                dp[j] = Math.max(dp[j], dp[j - stones[i]] + stones[i]);
            }
        }
        return sum - dp[tar] - dp[tar];
    }
}
